package com.demo.main.servlet;

import com.demo.main.entity.Book;
import com.demo.main.service.BookService;
import com.demo.main.utils.CommonUtil;
import com.demo.main.utils.JDBCUtil;
import com.demo.main.utils.JSONUtil;
import com.demo.main.utils.ServletUtil;
import com.demo.main.vo.BookVo;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.demo.main.utils.ServletUtil.PERMISSION_PATH_ADMIN;
import static com.demo.main.utils.ServletUtil.PERMISSION_PATH_USER;

@WebServlet({PERMISSION_PATH_USER + "/books_condition",
        PERMISSION_PATH_USER + "/borrow",
        PERMISSION_PATH_USER + "/return",
        PERMISSION_PATH_ADMIN + "/books_condition",
        PERMISSION_PATH_ADMIN + "/book_add",
        PERMISSION_PATH_ADMIN + "/book_edit",
        PERMISSION_PATH_ADMIN + "/book_delete",
        PERMISSION_PATH_ADMIN + "/book_batch_delete"})
public class BookServlet extends HttpServlet {

    private final BookService bookService = new BookService();


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ServletUtil servletUtil = new ServletUtil(request, response);
        switch (servletUtil.getServletPath()) {
            case PERMISSION_PATH_USER + "/books_condition":
                BookVo bookVo = servletUtil.convertRequestParameter(BookVo.class);

                servletUtil.handlePaginationAndCondition(
                        bookService::findBookVoPageCountByCondition,
                        bookVo,
                        bookService::findBookVoBySpecifiedCondition,
                        PERMISSION_PATH_USER + "/view/book");
                break;
            case PERMISSION_PATH_USER + "/borrow":
                // ajax
                Integer bookId = servletUtil.getParameterAs("bookId", Integer.class);

                JDBCUtil.StoredProcedureResult storedProcedureResult =
                        bookService.borrowBook(servletUtil.getSessionUserId(Integer.class), bookId, CommonUtil.BORROW_DAYS);

                Map<String, Object> resultMap = new HashMap<>();

                resultMap.put("book", bookService.findBookVoById(bookId));
                resultMap.put("message", storedProcedureResult.getMessage());
                resultMap.put("isSuccess", storedProcedureResult.isSuccess());

                response.getWriter().println(JSONUtil.mapToJson(resultMap));

                break;
            case PERMISSION_PATH_USER + "/return":
                // ajax
                bookId = servletUtil.getParameterAs("bookId", Integer.class);

                storedProcedureResult =
                        bookService.returnBook(servletUtil.getSessionUserId(Integer.class), bookId);

                resultMap = new HashMap<>();

                resultMap.put("book", bookService.findBookVoById(bookId));
                resultMap.put("message", storedProcedureResult.getMessage());
                resultMap.put("isSuccess", storedProcedureResult.isSuccess());

                response.getWriter().println(JSONUtil.mapToJson(resultMap));

                break;
            case PERMISSION_PATH_ADMIN + "/books_condition":
                bookVo = servletUtil.convertRequestParameter(BookVo.class);

                servletUtil.handlePaginationAndCondition(
                        bookService::findBookVoPageCountByCondition,
                        bookVo,
                        bookService::findBookVoBySpecifiedCondition,
                        PERMISSION_PATH_ADMIN + "/view/book_management");
                break;

            case PERMISSION_PATH_ADMIN + "/book_add":
                Book book = servletUtil.convertRequestParameter(Book.class);
                bookService.addOne(book);
                servletUtil.forward(PERMISSION_PATH_ADMIN + "/view/book_management");
                break;
            case PERMISSION_PATH_ADMIN + "/book_edit":

                book = servletUtil.convertRequestParameter(Book.class);
                bookService.updateById(book);
                servletUtil.forward(PERMISSION_PATH_ADMIN + "/view/book_management");

                break;
            case PERMISSION_PATH_ADMIN + "/book_delete":
                // ajax
                bookId = servletUtil.getParameterAs("bookId", Integer.class);
                bookService.deleteById(bookId);
                resultMap = new HashMap<>();

                resultMap.put("message", "删除成功");
                resultMap.put("isSuccess", true);

                response.getWriter().println(JSONUtil.mapToJson(resultMap));

                break;
            case PERMISSION_PATH_ADMIN + "/book_batch_delete":
                String idsString = request.getParameter("ids");
                if (idsString != null && !idsString.isEmpty()) {
                    String[] idsArray = idsString.split(",");
                    List<Integer> bookIds = new ArrayList<>();
                    for (String id : idsArray) {
                        try {
                            bookIds.add(Integer.parseInt(id.trim()));
                        } catch (NumberFormatException e) {
                            System.err.println("Invalid book ID: " + id);
                        }
                    }

                    try {
                        bookService.batchDeleteByIds(bookIds);
                        PrintWriter out = response.getWriter();
                        out.print("删除成功");
                        out.flush();
                    } catch (Exception e) {
                        PrintWriter out = response.getWriter();
                        out.print("删除失败");
                        out.flush();
                    }
                }
                break;
        }
    }

}
